package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.Room;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IRoomService;
import com.zzyl.nursing.vo.BedVo;
import com.zzyl.nursing.vo.DeviceInfo;
import com.zzyl.nursing.vo.RoomVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 房间Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-26
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询房间
     *
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }

    /**
     * 查询房间列表
     *
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        boolean flag = save(room);
        deleteCache();
        return flag ? 1 : 0;
    }

    /**
     * 修改房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {

        boolean flag = updateById(room);
        deleteCache();
        return flag ? 1 : 0;
    }

    /**
     * 批量删除房间
     *
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {

        boolean flag = removeByIds(Arrays.asList(ids));
        deleteCache();
        return flag ? 1 : 0;
    }

    /**
     * 根据楼层 id 获取房间视图对象列表
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }


    /**
     * 获取所有房间（负责老人）
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }

    /**
     * 根据房间id查询房间数据(楼层、房间、价格)
     *
     * @param id
     * @return
     */
    @Override
    public RoomVo getRoomById(Long id) {

        RoomVo roomVo = (RoomVo) redisTemplate.opsForValue().get(CacheConstants.ROOM_KEY);
        if (ObjectUtil.isNotEmpty(roomVo)) {
            return roomVo;
        }

        // 查询数据
        roomVo = roomMapper.getRoomById(id);

        // 缓存数据到redis中
        redisTemplate.opsForValue().set(CacheConstants.ROOM_KEY, roomVo);

        return roomVo;
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取房间中的智能设备及数据
     *
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {

        // 1、从数据库中获取房间、老人、床位关联的数据
        List<RoomVo> roomVoList = roomMapper.getRoomsWithDeviceByFloorId(floorId);
        if (CollUtil.isEmpty(roomVoList)) {
            return Collections.emptyList();
        }

        // 2、从redis中获取房间或者床位关联的设备数据信息
        roomVoList.forEach(r -> {

            // 2.1、获取房间关联的设备上报数据
            List<DeviceInfo> roomDeviceInfoList = r.getDeviceVos();
            if (CollUtil.isNotEmpty(roomDeviceInfoList)) {
                roomDeviceInfoList.forEach(d -> {
                    String deviceDataJSON = (String) stringRedisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_DATA_LATEST, d.getIotId());
                    if (StrUtil.isNotBlank(deviceDataJSON)) {
                        List<DeviceData> deviceDataList = JSONUtil.toList(deviceDataJSON, DeviceData.class);
                        d.setDeviceDataVos(deviceDataList);
                    }
                });
            }

            // 2.2、获取床位关联的设备上报数据
            List<BedVo> bedVoList = r.getBedVoList();
            if (CollUtil.isNotEmpty(bedVoList)) {
                bedVoList.forEach(b -> {
                    List<DeviceInfo> bedDeviceInfoList = b.getDeviceVos();
                    if (CollUtil.isNotEmpty(bedDeviceInfoList)) {
                        bedDeviceInfoList.forEach(bd -> {
                            String deviceDataJSON = (String) stringRedisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_DATA_LATEST, bd.getIotId());
                            if (StrUtil.isNotBlank(deviceDataJSON)) {
                                List<DeviceData> deviceDataList = JSONUtil.toList(deviceDataJSON, DeviceData.class);
                                bd.setDeviceDataVos(deviceDataList);
                            }
                        });
                    }
                });
            }
        });
        return roomVoList;
    }

    /**
     * 删除redis中的旧缓存
     */
    private void deleteCache() {
        redisTemplate.delete(CacheConstants.ROOM_KEY);
    }
}
